<?php

namespace app\admin\controller\pt;

use app\common\controller\Backend;
use app\common\library\Export as ExportLib;
use app\admin\model\Admin as AdminModel;
use app\admin\model\pt\LaborLog as LogModel;
use Carbon\Carbon;
use think\Db;

/**
 * 劳务公司管理
 *
 * @icon fa fa-circle-o
 */
class Labor extends Backend
{

    /**
     * Labor模型对象
     * @var \app\admin\model\pt\Labor
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\pt\Labor;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where($where)
                ->with(['admin'])
                ->order($sort, $order)
                ->paginate($limit);
            $rows = $list->items();
            $adminIds = [];
            foreach ($rows as $r) {
                $admins = $r['admin'];
                if (!empty($admins)) {
                    foreach ($admins as $a) {
                        $adminIds[] = $a['admin_id'];
                    }
                }
            }
            $adminInfos = AdminModel::where('id', 'in', $adminIds)->select();
            $adminData = [];
            foreach ($adminInfos as $ai) {
                $adminData[$ai['id']] = $ai['username'];
            }

            foreach ($rows as &$r) {
                $adminStr = "";
                $admins = $r['admin'];
                unset($r['admin']);
                if (!empty($admins)) {
                    foreach ($admins as $a) {
                        if (isset($adminData[$a['admin_id']])) {
                            $adminStr .= $adminData[$a['admin_id']] . "<br />";
                        }
                    }
                }
                $r['admin_str'] = trim($adminStr , '<br />');
            }
            unset($r);

            $result = array("total" => $list->total(), "rows" => $rows);

            return json($result);
        }
        return $this->view->fetch();
    }

    public function statistic()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            // 查询劳务公司
            $monthId = date('Ym', strtotime($this->request->get('query_date') . "-01"));
            $labors = $this->model
                           ->where($where)
                           ->with('admin')
                           ->select();
            $adminIds = [];
            $adminLogs = [];
            $rows = [];
            foreach ($labors as $l) {
                $tmp = [
                    'labor_name'  => $l->name,
                    'add_total' => 0,
                    'del_total' => 0,
                    'absent_total' => 0,
                    'del_percent' => 0,
                    'absent_percent' => 0,
                    'id' => $l->id,
                    'admin_ids' => [],
                ]; 
                $admins = $l['admin'];
                if (!empty($admins)) {
                    foreach ($admins as $a) {
                        $adminIds[] = $a['admin_id'];
                        $tmp['admin_ids'][] = $a['admin_id'];
                        if (!isset($adminLogs[$a['admin_id']])) {
                            $adminLogs[$a['admin_id']] = [
                                'add_total' => 0,
                                'del_total' => 0,
                            ];
                        }
                    }
                }
                $rows[] = $tmp;
            }
            // 查找当月所有
            $logs = LogModel::where('date_id', 'like', $monthId . '%')
                    ->where('admin_id', 'in', $adminIds)->select();
            foreach ($logs as $log) {
                if (isset($adminLogs[$log['admin_id']])) {
                    if ($log['log_action'] == 'add') {
                        // 新增的
                        $adminLogs[$log['admin_id']]['add_total']++;
                    } else if ($log['log_action'] == 'del') {
                        // 删除的
                        $adminLogs[$log['admin_id']]['del_total']++;
                    }
                }
            }
            $prevDateId = date('Ymd', strtotime('-1 day'));
            // 查找到截止时间前一天未打卡的
            $dutyList = Db::name('pt_duty_list')
              ->alias("duty")
              ->join('pt_person person', 'duty.pt_person_id = person.id')
              ->field('duty.clock_json, duty.id, person.pt_labor_id')
              ->where('duty.date_id', 'like', $monthId . '%')
              ->where('duty.date_id', '<=', $prevDateId)
              ->where('person.pt_labor_id', '<>', 0)
              ->select();
            $absents = [];
            foreach ($dutyList as $d) {
                if (empty($d['clock_json'])) {
                    if (!isset($absents[$d['pt_labor_id']])) {
                        $absents[$d['pt_labor_id']] = 1;
                    } else {
                        $absents[$d['pt_labor_id']]++;
                    }
                }
            }
            foreach ($rows as &$r) {
                if (isset($absents[$r['id']])) {
                    $r['absent_total'] = $absents[$r['id']];
                }
                foreach ($r['admin_ids'] as $aid) {
                    if (isset($adminLogs[$aid])) {
                        $r['add_total'] += $adminLogs[$aid]['add_total'];
                        $r['del_total'] += $adminLogs[$aid]['del_total'];
                    }
                }
                // 计算百分比
                if (!empty($r['add_total'])) {
                    $r['del_percent'] = round($r['del_total'] / $r['add_total'] * 100, 2);
                    $r['absent_percent'] = round($r['absent_total'] / $r['add_total'] * 100,2);
                }
            }
            unset($r);

            $result = array("total" => count($rows), "rows" => $rows);

            return json($result);
        }
        $this->view->assign('query_date', date('Y-m'));
        return $this->view->fetch();
    
    }

    public function export()
    {
        $queryDate = $this->request->get('query_date');
        $laborId = $this->request->get('labor_id');
        $monthId = date('Ym', strtotime($queryDate . "-01"));

        $labors = $this->model
                       ->where('id', $laborId)
                       ->with('admin')
                       ->find();
        if (!$labors) {
            $this->error('劳务公司信息未找到');
        }
        $adminIds = [];
        $adminLogs = [];
        $laborData= [];
        $laborData = [
            'labor_name'  => $labors->name,
            'add_total' => [],
            'del_total' => [],
            'absent_total' => [],
            'id' => $labors->id,
            'admin_ids' => [],
        ]; 
        $adminLogs['add_total'] = [];
        $adminLogs['del_total'] = [];
        $admins = $labors->admin;
        if (!empty($admins)) {
            foreach ($admins as $a) {
                $adminIds[] = $a['admin_id'];
            }
        }

        $personIds = [];
        // 查找当月所有
        $logs = Db::name('pt_labor_log')
          ->alias('log')
          ->join('pt_person person', 'log.person_id = person.id')
          ->field('log.*, person.user_name')
          ->where('log.date_id', 'like', $monthId . '%')
          ->where('log.admin_id', 'in', $adminIds)
          ->select();
        foreach ($logs as $log) {
            if ($log['log_action'] == 'add') {
                // 新增的
                $adminLogs['add_total'][] = $log;
            } else if ($log['log_action'] == 'del') {
                // 删除的
                $adminLogs['del_total'][] = $log;
            }
        }
        $prevDateId = date('Ymd', strtotime('-1 day'));
        // 查找到截止时间前一天未打卡的
        $dutyList = Db::name('pt_duty_list')
          ->alias("duty")
          ->join('pt_person person', 'duty.pt_person_id = person.id')
          ->field('duty.date_id,duty.depart_name, duty.job_name, person.user_name')
          ->where('duty.date_id', 'like', $monthId . '%')
          ->where('duty.date_id', '<=', $prevDateId)
          ->where('person.pt_labor_id', $laborId)
          ->select();
        $absents = [];
        foreach ($dutyList as $d) {
            if (empty($d['clock_json'])) {
                $absents[] = $d;
            }
        }
        $logData = [];
        foreach ($adminLogs['add_total'] as $l) {
            $logData[] = [
                '新增',
                date('Y-m-d', strtotime($l['date_id'])),
                $l['depart_name'],
                $l['job_name'],
                $l['user_name'],
            ];
        }
        foreach ($adminLogs['del_total'] as $l) {
            $logData[] = [
                '删除',
                date('Y-m-d', strtotime($l['date_id'])),
                $l['depart_name'],
                $l['job_name'],
                $l['user_name'],
            ];
        }
        foreach ($absents as $l) {
            $logData[] = [
                '缺岗',
                date('Y-m-d', strtotime($l['date_id'])),
                $l['depart_name'],
                $l['job_name'],
                $l['user_name'],
            ];
        }


        // $file = '/uploads/export/'.date('Ymd').'/'.$laborData['labor_name'] .'_' . uniqid() .'.xlsx';
        $savePath = '/uploads/export/'.date('Ymd') ;
        $filename =  $laborData['labor_name'] .'_' . uniqid() .'.xlsx';
        $filePath = ROOT_PATH . 'public' . $savePath;
        $fileSaveName =  $filePath  . '/' . $filename;
        if (!is_dir($filePath)) {
            @mkdir($filePath, 0755, true);
        }
        $headers = [
            '类型',
            '岗位日期',
            '部门名称',
            '岗位名称',
            '人员姓名',
        ];
        $exportLib = new ExportLib($headers, $logData, $fileSaveName, 'save');
        $exportLib->createTable();
        $this->success('导出成功', '', ['file' => cdnurl($savePath . '/' .$filename, true)]);
        /*
        $result = ['file' => cdnurl($savePath . '/' . $filename, true)];
        return json($result);
         */
    
    }

}
